package piwan;

import java.awt.event.MouseEvent;
import java.util.LinkedList;

public class RegionSelector extends EventHandler {
	public static final Colour INVALID_COLOUR = new Colour(0.3,0.3,0.3,0.9);
	public static final Colour SELECTABLE_COLOUR = new Colour(1.0,1.0,1.0,1.0);
	
	public interface Listener {
		public void selected( Region r, MouseEvent e );
		public Colour hovered( Region r, MouseEvent e );
	}
	
	public RegionSelector(UserGame ug) {
		this.ug = ug;
		rnd = ug.getWorldRenderer().getBorderRenderer();
		world = ug.getWorld();
		cam = ug.getCamera();
		
		border = rnd.new Border();
		enable();
	}
	
	public void addListener( Listener l ) {
		lsts.add(l);
		if(hover!=null) {
			Colour c = l.hovered(hover, lastHoverEvent);
			if( c!= null )
				border.setColour(c);
		}
		
	}
	public void removeListener( Listener l ) { lsts.remove(l); hover = null;}
	
	public void enable() {
		hover = null;
		ug.addEventHandler(this);
	}
	
	public void disable() {
		border.remove();
		ug.removeEventHandler(this);
	}
	
	public void suppressUnhover() { hover=null; }
	
	public boolean onMouseMotion(MouseEvent e) {
		Region newHover = world.getRegionAt( cam.getWorldMouse() );
		if(newHover!=hover) {
			if(hover!=null)
				border.remove();
			
			if(newHover != null || hover!=null) {
				lastHoverEvent = e;
				Colour c = INVALID_COLOUR;
				for(Listener l:lsts) {
					Colour ret = l.hovered(newHover,e);
					if(ret!=null)
						c = ret;
				}	
				
				setHover(newHover,c);
			} else
				hover = null;
		}
		
		return false;
	}
	
	private void setHover( Region newHover, Colour c ) {
		hover = newHover;
		if(hover!=null) {
			border.setPolygons(hover.getPolygons());
			border.setColour(c);
			border.add();
		} else
			border.remove();
	}
	
	public boolean onMousePressed(MouseEvent e) {
		onMouseMotion(e);
		
		if(hover!=null)
			for(Listener l: lsts)
				l.selected(hover,e);
		return false;
	}
	
	private UserGame ug = null;
	private BorderRenderer rnd = null;
	private World world = null;
	private Camera cam = null;
	private LinkedList<Listener> lsts = new LinkedList<Listener>();
	private Region hover = null;
	private BorderRenderer.Border border = null;
	private MouseEvent lastHoverEvent = null;
}
